import 'package:dio/dio.dart';
import 'config.dart';
import 'http_header.dart';
import 'http_request_model.dart';

class HttpRequest {
  static final BaseOptions baseOptions = BaseOptions(
      baseUrl: HttpConfig.baseURL,
      connectTimeout: HttpConfig.timeout,
      headers: {
        HttpHeaders.tokenHeader: "eyJhbGciOiJIUzI1NiJ9.eyJwaG9uZSI6IjE4NTM4MDg5ODA1IiwibmFtZSI6IuS9leWdpOm5jyIsInVzZXJUeXBlIjoxLCJpZCI6MTE2MTIsImV4cCI6MTY0MTI3NzUwNywidXNlcklkIjoiNzg5ODgwOTExMzIyNjc3MjQ4IiwiaWF0IjoxNjQwNjcyNzA3fQ.NmV7HM7n9wcRziSr0PYXZXHHbos-jL-R2EeDcXH3wcY",
      }
  );
  static final Dio dio = Dio(baseOptions);

  static Future<T> request<T>(String url, {
                      String method = "get",
                      Map<String, dynamic> params,
                      Interceptor inter}) async {

    // 1.创建单独配置
    final options = Options(method: method);

    // 全局拦截器
    // 创建默认的全局拦截器
    Interceptor dInter = InterceptorsWrapper(
      onRequest: (options) {
        // print("\n================== 请求数据 ==========================");
        // print("url = ${options.uri.toString()}");
        // print("headers = ${options.headers}");
        // print("params = ${options.data}");
        return options;
      },
      onResponse: (response) {
        // print("\n================== 响应数据 ==========================");
        // print("code = ${response.statusCode}");
        // print("data = ${response.data}");
        // print("\n");
        return response;
      },
      onError: (err) {
        // print("\n================== 错误响应数据 ======================");
        // print("type = ${err.type}");
        // print("message = ${err.message}");
        // print("stackTrace = ${err.error}");
        // print("\n");
        return err;
      }
    );
    List<Interceptor> inters = [dInter];

    // 请求单独拦截器
    if (inter != null) {
      inters.add(inter);
    }

    // 统一添加到拦截器中
    dio.interceptors.addAll(inters);

    // 2.发送网络请求
    try {
      Response response = await dio.request(url, queryParameters: params, options: options);
      HttpResponse responseModel = HttpResponse.fromJson(response.data);
      // print("===responseModel.data===${responseModel.data}");
      return responseModel.data;
    } on DioError catch(e) {
      return Future.error(e);
    }
  }
}